package com.xinqi.common.base.dto.utils;

import com.xinqi.common.base.dto.QuestionBaseDTO;
import com.xinqi.common.base.enums.QuestionTypeEnum;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.common.base.utils.number.BigDecimals;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author linkai
 * @date 2023/3/28
 */
public interface QuestionUtils {
    /**
     * 空数组
     */
    String[] EMPTY_ARRAY = new String[0];

    static String[] answer2Array(QuestionTypeEnum type, String answer) {
        if (type == null || StringUtils.isBlank(answer)) {
            return EMPTY_ARRAY;
        }
        switch (type) {
            case ANSWER_JUDGE:
            case ANSWER_RADIO:
                return new String[]{answer};
            case ANSWER_MULTIPLE:
            case ANSWER_INDEFINITE:
                return answer.split(",", -1);
            case ANSWER_CLOZE:
                return answer.split("\n", -1);
        }
        return EMPTY_ARRAY;
    }

    static List<String> answer2List(QuestionTypeEnum type, String answer) {
        return Arrays.asList(answer2Array(type, answer));
    }

    static QuestionStats status(List<QuestionBaseDTO> questionList) {
        if (CollectionUtils.isEmpty(questionList)) {
            return QuestionStats.empty();
        }
        BigDecimal totalScore = BigDecimal.ZERO;
        int questionTotal = 0;
        int subjectiveQuestionNum = 0;
        int objectiveQuestionNum = 0;
        Set<String> questionTypeSet = new HashSet<>(10);
        for (QuestionBaseDTO questionBaseDTO : questionList) {
            totalScore = BigDecimals.add(Optional.ofNullable(questionBaseDTO.getScore()).orElse(BigDecimal.ZERO), totalScore);
            questionTotal++;
            String type = questionBaseDTO.getType();
            boolean objective = QuestionTypeEnum.isObjective(type);
            if (objective) {
                objectiveQuestionNum++;
            } else {
                subjectiveQuestionNum++;
            }
            questionTypeSet.add(type);
        }
        return QuestionStats.of(totalScore, questionTotal, questionTypeSet.size(), subjectiveQuestionNum, objectiveQuestionNum);
    }

    static QuestionStats status(String questionJson) {
        return status(json(questionJson));
    }

    static List<QuestionBaseDTO> json(String questionJson) {
        if (StringUtils.isBlank(questionJson)) {
            return Collections.emptyList();
        }
        return JSON.parseList(questionJson, QuestionBaseDTO.class);
    }
}
